package com.zhan.signalling.store.tablestore;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.alicloud.openservices.tablestore.timeline.ScanParameter;
import com.alicloud.openservices.tablestore.timeline.ScanParameterBuilder;
import com.alicloud.openservices.tablestore.timeline.Timeline;
import com.alicloud.openservices.tablestore.timeline.TimelineEntry;
import com.alicloud.openservices.tablestore.timeline.message.IMessage;
import com.alicloud.openservices.tablestore.timeline.store.IStore;

public class MessageOperation {
	
	private IStore store;
	
	public MessageOperation(IStore store) {
		this.store = store;
	}
	
	/**
	 * 消息存储
	 * @param message
	 */
	public long save(String platForm_groupId, IMessage message) {
		Timeline storeTimeline = new Timeline(platForm_groupId,store);
		TimelineEntry entry = storeTimeline.store(message);
		return entry.getSequenceID();
	}
	
	
	/**
	 * 获取历史信息 返回最近指定序号前999条
	 * @param platForm
	 * @param groupId
	 * @param seqId 最后一条信息序列号 大于
	 * @return
	 */
	public List<IMessage> getHistoryMessage(String platForm_groupId, Long seqId){
		List<IMessage> messages = new ArrayList<>();
		Timeline syncTimeline = new Timeline(platForm_groupId,store);
		if(seqId == null || seqId <= 0) {
			return messages;
		}
		
		ScanParameter scanParameter = ScanParameterBuilder
										.scanForward()
										.from(0)
										.to(seqId + 1) //包含seqId行
										.maxCount(1000)
										.build();
		Iterator<TimelineEntry> iterator = syncTimeline.scan(scanParameter);
		while(iterator.hasNext()) {
			TimelineEntry entry = iterator.next();
			long curSeqId = entry.getSequenceID();
			IMessage message = entry.getMessage();
			message.addAttribute("seqId", String.valueOf(curSeqId));
			messages.add(message);
		}
		return messages;
	}
	
}
